package cn.jdy.lhkgaj.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.lhkgaj.entity.LhkgajNews;
import cn.jdy.lhkgaj.service.LhkgajExeclService;
import cn.jdy.lhkgaj.service.LhkgajNewsService;
import cn.jdy.platform.entity.ConfValue;
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
 
import org.apache.poi.hssf.usermodel.HSSFCell; 
import org.apache.poi.hssf.usermodel.HSSFRow; 
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.poifs.filesystem.POIFSFileSystem; 
/**
 * @desc 投稿控制类
 * @author nignqian
 * @date   2016-10-26
 */
@Controller
@RequestMapping("/lhkgajarticle")
public class LhkgajArticleCtrl extends BaseCtrl {

	@Autowired
	private LhkgajNewsService newsService;
	@Autowired
	private LhkgajExeclService execlService;
	//默认列表路径
	private static String viewName = "redirect:/lhkgajarticle/list?s=";

	/**
	 * 老河口公安分局
	 * 初始化,仅作页面跳转作用
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(LhkgajNews entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/articleList.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		mv.addObject("classList",  this.confService.djgajListColumn(GlobalConstant.TYPE_NEWS));
		return mv;
	}
	
	/**
	 * 特警
	 * 初始化,仅作页面跳转作用
	 * @return
	 */
	@RequestMapping("/lists")
	public ModelAndView lists(LhkgajNews entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/articleLists.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "成功！");break;
				case '2': mv.addObject("msg", "删除成功！");break;
				case '3': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		return mv;
	}

	/**
	 * 老河口公安分局
	 * 异步查询
	 * 投稿文章状态为未审核
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(LhkgajNews news, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			news.setStatus("0");//未审核
			jsonMap.put("dataList", newsService.query1(news, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", newsService.count1(news, fromDate, toDate));
			jsonMap.put("iTotalRecords", newsService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}

	/**
	 * 
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}
	
	/**
	 * 老河口公安分局
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/articleDetail.jsp");
		mv.addObject("column", this.confService.queryByType(21, 0L));
		LhkgajNews news = this.newsService.find(id);
		if(id!=null){
		mv.addObject("data", news);
		mv.addObject("ctime", DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		}
		if(id==null){
			
			mv.addObject("ctime", DateUtil.getCurrentDate(DateUtil._DEFAULT2));
			}
		// 获得系统所有签收单位
		List<ConfValue> list = confService.queryByType(72,null);
		mv.addObject("deptList", list);
		
		LhkgajNews datas = this.newsService.find(id);
		LhkgajNews datanewsNews = new LhkgajNews();
		mv.addObject("data", id==null||id==0 ? datanewsNews : datas);
		User user = getUser();
		mv.addObject("username", user.getUsername());
		return mv;
	}

	/**
	 * 老河口公安分局
	 * 保存（更新）投稿
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	public ModelAndView save(LhkgajNews news, Long pid) {
		ModelAndView mv = new ModelAndView();
		try {
			//如果二级新闻类别为空，则使用一级类别
      if(null == news.getColumnId()) {
        news.setColumnId(pid);
      }
	      String names = news.getDepartment();
	      if( names==null){
	    	  User user = getUser();
	    	  news.setUserid(user.getId());
	    	  names = user.getUsername();
	      }
	      news.setUsername(names);
			if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
				news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
			}//老河口公安分局
			 if(news.getId()==null) {// 新增文章
					//
					news.setDepartment(news.getUsername());
					news.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
					this.newsService.save(news);
					mv.setViewName(this.viewName.concat("1"));
					}else{
		//更新文章
//			news.setCreateTime(news.getCreateTime());//老河口公安分局
			this.newsService.update(news);
			mv.setViewName(this.viewName.concat("2"));
	    // 清理文章缓存
	    NginxPurgeCacheUtil.purge(2, news.getId());
	    }
		// 清理栏目列表缓存
		NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "稿件保存异常！", e);
		}

		return mv;
	}
	/**
	 * 老河口公安分局
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.newsService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
            NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return mv;
	}
	
	private HSSFWorkbook wb = null;// book [includes sheet] 
    private HSSFSheet sheet = null; 
    private HSSFRow row = null; 
     
    private int sheetNum = 0; // 第sheetnum个工作表 
    private int rowNum = 0; 
    private FileInputStream fis = null; 
    private File file = null; 
 
    public void ExcelReader() { 
    } 
 
    public void ExcelReader(File file) { 
        this.file = file; 
    } 
 
    public void setRowNum(int rowNum) { 
        this.rowNum = rowNum; 
    } 
 
    public void setSheetNum(int sheetNum) { 
        this.sheetNum = sheetNum; 
    } 
 
    public void setFile(File file) { 
        this.file = file; 
    } 
 
    /**
     * 读取excel文件获得HSSFWorkbook对象
     */ 
    public void open() throws IOException { 
        fis = new FileInputStream(file); 
        wb = new HSSFWorkbook(new POIFSFileSystem(fis)); 
        fis.close(); 
    } 
 
    /**
     * 返回sheet表数目
     * 
     * @return int
     */ 
    public int getSheetCount() { 
        int sheetCount = -1; 
        sheetCount = wb.getNumberOfSheets(); 
        return sheetCount; 
    } 
 
    /**
     * sheetNum下的记录行数
     * 
     * @return int
     */ 
    public int getRowCount() { 
        if (wb == null) 
            System.out.println("=============WorkBook为空=============="); 
        HSSFSheet sheet = wb.getSheetAt(this.sheetNum); 
        int rowCount = -1; 
        rowCount = sheet.getLastRowNum(); 
        return rowCount; 
    } 
 
    /**
     * 读取指定sheetNum的rowCount
     * 
     * @param sheetNum
     * @return int
     */ 
    public int getRowCount(int sheetNum) { 
        HSSFSheet sheet = wb.getSheetAt(sheetNum); 
        int rowCount = -1; 
        rowCount = sheet.getLastRowNum(); 
        return rowCount; 
    } 
 
    /**
     * 得到指定行的内容
     * 
     * @param lineNum
     * @return String[]
     */ 
    public String[] readExcelLine(int lineNum) { 
        return readExcelLine(this.sheetNum, lineNum); 
    } 
 
    /**
     * 指定工作表和行数的内容
     * 
     * @param sheetNum
     * @param lineNum
     * @return String[]
     */ 
    public String[] readExcelLine(int sheetNum, int lineNum) { 
        if (sheetNum < 0 || lineNum < 0) 
            return null; 
        String[] strExcelLine = null; 
        try { 
            sheet = wb.getSheetAt(sheetNum); 
            row = sheet.getRow(lineNum); 
 
            int cellCount = row.getLastCellNum(); 
            strExcelLine = new String[cellCount + 1]; 
            for (int i = 0; i <= cellCount; i++) { 
                strExcelLine[i] = readStringExcelCell(lineNum, i); 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return strExcelLine; 
    } 
 
    /**
     * 读取指定列的内容
     * 
     * @param cellNum
     * @return String
     */ 
    public String readStringExcelCell(int cellNum) { 
        return readStringExcelCell(this.rowNum, cellNum); 
    } 
 
    /**
     * 指定行和列编号的内容
     * 
     * @param rowNum
     * @param cellNum
     * @return String
     */ 
    public String readStringExcelCell(int rowNum, int cellNum) { 
        return readStringExcelCell(this.sheetNum, rowNum, cellNum); 
    } 
 
    /**
     * 指定工作表、行、列下的内容
     * 
     * @param sheetNum
     * @param rowNum
     * @param cellNum
     * @return String
     */ 
    public String readStringExcelCell(int sheetNum, int rowNum, int cellNum) { 
        if (sheetNum < 0 || rowNum < 0) 
            return ""; 
        String strExcelCell = ""; 
        try { 
            sheet = wb.getSheetAt(sheetNum); 
            row = sheet.getRow(rowNum); 
 
            if (row.getCell((short) cellNum) != null) { // add this condition 
 
                // judge 
 
                switch (row.getCell((short) cellNum).getCellType()) { 
                case HSSFCell.CELL_TYPE_FORMULA: 
                    strExcelCell = "FORMULA "; 
                    break; 
                case HSSFCell.CELL_TYPE_NUMERIC: { 
                    strExcelCell = String.valueOf(row.getCell((short) cellNum) 
                            .getNumericCellValue()); 
                } 
                    break; 
                case HSSFCell.CELL_TYPE_STRING: 
                    strExcelCell = row.getCell((short) cellNum) 
                            .getStringCellValue(); 
                    break; 
                case HSSFCell.CELL_TYPE_BLANK: 
                    strExcelCell = ""; 
                    break; 
                default: 
                    strExcelCell = ""; 
                    break; 
                } 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return strExcelCell; 
    }
}
